<?php

namespace App\Http\Controllers\Api\v1;

use App\Models\Question;
use App\Models\Article;
use App\Models\Banner;
use App\Models\Api\Recode;
use App\Models\System;
use App\Tools\Astrolog\Astrolog;
use App\Models\Api\FortuneCache;
use App\Tools\Base\Common;
//use App\Tools\Base\Auth;
use App\Tools\Astrocalendar;
use App\Models\Api\Strastro;
use App\Tools\Validates\Strastro as Star;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\Api\v1\Everyday\IndexController as Day;
use DB;
class IndexController extends Controller
{

     public $user = []; //定义
     public $nowData=[];
    /**
     * @return \Illuminate\Http\JsonResponse
     * 首页查询
     */
    public function index(Request $request){

        $map = ['uid' => $request->uid, 'isself' => 1];

       // \Log::info('editRecord：' . var_export($map));
        // 调用当前自己的档案进行运势运算

         $recode_info = (new Recode())->getSelfRecode($map);

         if (empty($recode_info)) {
            return show(config('code.denied'), '用户信息获取失败,请重新登录', [], 403);
        }


        $recode_info['longitude'] = ($recode_info['long_deg'] + $recode_info['long_min'] / 60 ) * $recode_info['ew'];

        $recode_info['latitude'] = ($recode_info['lat_deg'] + $recode_info['lat_min'] / 60 ) * $recode_info['ns'];
        // 开始获取首页 日运主题 && 宜忌
        $dailyFortune = new Day();

        //如果错误的话，也返回数据，否则首页就加载失败了
        $lucky_name = '';//宜
        $avoid = '';//忌
        $revive_day = ['name' => '', 'star_level' => 0, 'tips' => '', 'icon_url' => '', 'tips_url' => ''];//**之日
        $sun_in_sign = 1;//周运星座
        $tips = '';//今日天象
        $time_now = time();
        $is_use_cache = 0;
        if ($is_use_cache)
        {//匹配返回的数据，放入缓存中
            $map = ['time' => $time_now, 'recode' => $recode_info];

            try
            {
                $fortune_cache = (new FortuneCache())->getHomePageFortune($map);
                $lucky_name = $fortune_cache['lucky_name'];
                $avoid = $fortune_cache['forbid_name'];
                $revive_day = $fortune_cache['revive_day'];
                $sun_in_sign = $fortune_cache['sun_in_sign'];
                $tips = $fortune_cache['tips'];
            }
            catch (\Exception $e)
            {
                // 错误信息写入日志
                \Log::info('首页获取日运缓存数据错误:' . 'uid=[' . $request->uid . ']'.$e->getMessage());
            }


        } else
        {

            $dailyTime = strtotime(date('Y-m-d', $time_now) . ' 12:00:00');
            $timeinfo = [
                'year' => date('Y', $dailyTime),
                'month' => date('m', $dailyTime),
                'day' => date('d', $dailyTime),
                'hour' => date('H', $dailyTime),
                'minute' => date('i', $dailyTime),
            ];
            $timeinfo['timezone'] = 8;
            $timeinfo['is_summer'] = isSummerTime($timeinfo['hour'], $timeinfo['minute'], 0,
            $timeinfo['month'], $timeinfo['day'], $timeinfo['year']) ? 1 : 0;

             $dailyFortune->astro = Astrolog::getInstance();
             $dailyFortune->astro
                ->setRecode1($recode_info)
                ->setAdvance($timeinfo)
                ->setExecPrefix(config('astrolog.prefix'))
                ->setIsAstrolabe(false)
                ->setUserSetting(config('astroset.setting1'))
                ->setGetDatas(['now', 'natal', 'transits', 'thirdprogressed'])
                ->getAstroDatas();

            $dailyFortune->nowData = $dailyFortune->astro->getDatas('now');
            $dailyFortune->natalData = $dailyFortune->astro->getDatas('natal');
            $dailyFortune->transitsData = $dailyFortune->astro->getDatas('transits');
            $dailyFortune->thirdprogressedData = $dailyFortune->astro->getDatas('thirdprogressed');

            $dailyFortune->active = $dailyFortune->getActive();
            $lucky_name = $dailyFortune->getSuitable($recode_info, $dailyTime, true);
            $forbid_name = $dailyFortune->getAvoid(true);
            $avoid = [];
            // 宜中出现过的，忌中不显示
            if (!empty($forbid_name)) foreach ($forbid_name as $avd) if (!in_array($avd, $lucky_name)) $avoid[] = $avd;

            $revive_day = $dailyFortune->getTopic($recode_info, $dailyTime, true);

            $sun_in_sign = $dailyFortune->natalData['planets'][0]['in_sign_id'] ?? 1;// 如失败 则为白羊座
            // 获取今日天象
            $timeinfo['hour'] = 0;
            $dailyFortune->nowData = $dailyFortune->astro
                ->setAdvance($timeinfo)
                ->setGetDatas(['now'])
                ->getAstroDatas()
                ->getDatas('now');

            $tips = $dailyFortune->getAstrologicalDetailst(time());
            //var_dump($tips);die;
            $overview              = $dailyFortune->init($recode_info['id'], strtotime(date('Y-m-d', time()) . ' 09:00:00'));
            $temp[]            = $overview['fortune_list'][4];
            $temp[]            = $overview['fortune_list'][3];
            $temp[]            = $overview['fortune_list'][1];
            $temp[]            = $overview['fortune_list'][0];
            $temp[]            = $overview['fortune_list'][6];
            $temp[]            = $overview['fortune_list'][2];
            $temp[]            = $overview['fortune_list'][5];
            $temp[]            = $overview['fortune_list'][7];
            $temp[]            = $overview['fortune_list'][8];
                //婚恋/学习/事业/财富/出行/健康/交际/家人/心情
            $fortune_list = $temp;
            //幸运色
           $lucky_symbol = $overview['lucky_symbol'];
        }

         $calendar =  (new Astrocalendar())->astroCalendar(date('Y', $dailyTime),date('m', $dailyTime),$timeinfo['timezone']);
         $changeData = (new \App\Models\CacheModel\zl2\AstroFortuneChange())->getIndexAstroFortuneChangeData($time_now, false);


         //$data['change_data'] = $changeData;
         $data = [
            'in_sign' => $sun_in_sign,
           // 'slides' => $slide,
           // 'buttons' => $buttons,
            'today_fortune' => [
                'revive_day' => $revive_day,
                'lucky_name' => $lucky_name,
                'forbid_name' => $avoid,
                'fortune_list'=>$fortune_list,
                'lucky_symbol'=>$lucky_symbol,
            ],
            'content' => '999',
            'astro_calendar'=>$calendar[intval(date('d', $dailyTime))],
            'change_data'=>$changeData,
            'today_astro' => [
                'time' => strtotime(date('Y-m-d', $time_now)),// 精确到天
                'tips' => $tips ?? '',
            ],
           // 'article' => $article,
            //展示屏蔽
            //'questions' =>$questions,
            'lucky_planet_switch' => false,// 幸运星功能开关
        ];

         return show(200,'首页加载成功',$data);
         //return show(200,'首页加载成功',(new \App\Tools\Aes())->encryptWithOpenssl(json_encode($data)));
    }
    public function getNow()
    {
        //1、检测当天天象
        //2、太阳在哪个星座（输出：太阳在某某座）
        //3、水、金、火、木、土是否逆行或停滞（速度低于平均速度的1/5）（输出：某星逆行，某星停滞）
        //4、日水金火木土天海冥是否与昨天24点的星座不同（输出：某某星进入某某座）
        //5、天象是否构成大十字，大风筝，大信封，大三角，T三角（输出：大十字，大风筝，大信封等）
        $tips = '';
        $time_now =time();
        $dailyTime = strtotime(date('Y-m-d', $time_now) . ' 12:00:00');
            $timeinfo = [
                'year' => date('Y', $dailyTime),
                'month' => date('m', $dailyTime),
                'day' => date('d', $dailyTime),
                'hour' => date('H', $dailyTime),
                'minute' => date('i', $dailyTime),
            ];
            $timeinfo['timezone'] = 8;
            $timeinfo['is_summer'] = isSummerTime($timeinfo['hour'], $timeinfo['minute'], 0,
            $timeinfo['month'], $timeinfo['day'], $timeinfo['year']) ? 1 : 0;
            $timeinfo['longitude'] = '116.59361';
            $timeinfo['latitude'] = '35.42018';
            $dailyFortune = Astrolog::getInstance();
            $dailyFortune
                ->setAdvance($timeinfo)
                ->setExecPrefix(config('astrolog.prefix'))
                ->setIsAstrolabe(false)
                ->setUserSetting(config('astroset.setting1'))
                ->setGetDatas(['now'])
                ->getAstroDatas();
        $nowData = $dailyFortune->getDatas('now');
        //$nowData = $this->nowData;

        $tx_planet = $nowData['planets'];// 天象行星数据

        $tx_structure = $nowData['structure'];// 天象行星结构数据


        $sun_deg = $tx_planet[0]['deg'];// 太阳的度数
        $sun_speed = $tx_planet[0]['speed'];// 太阳的度数

        $start_sign = modSignId(floor($sun_deg / 30) + 1);
        $end_sign = modSignId(floor(($sun_deg + $sun_speed)/30) + 1);

        if($start_sign == $end_sign)
        {
            $sign_name = explode('|',config('astrolog.sign_name')[$start_sign])[3];

            $tips .= '太阳在'.$sign_name;
        }
        else
        {
            $sign_name = explode('|',config('astrolog.sign_name')[$end_sign])[3];

            $tips .= '太阳进入'.$sign_name;
        }
         $merc_deg = $tx_planet[2]['deg'];// 太阳的度数
        $merc_speed = $tx_planet[2]['speed'];// 太阳的度数

        $start_sign = modSignId(floor($merc_deg / 30) + 1);
        $end_sign = modSignId(floor(($merc_deg + $merc_speed)/30) + 1);
         if($start_sign == $end_sign)
        {
            $sign_name = explode('|',config('astrolog.sign_name')[$start_sign])[3];
            $tips .= '水星在'.$sign_name;
        }
        else
        {
            $sign_name = explode('|',config('astrolog.sign_name')[$end_sign])[3];

            $tips .= '水星进入'.$sign_name;
        }

        foreach ([2,3,4,5,6,7,8,9] as $i)
        {
            $speed = $tx_planet[$i]['speed'];

            $average_speed = config('astrolog.speed')[$i];

            $p_name = explode('|',config('astrolog.planets_name')[$i])[3];

            if($speed < 0)
            {
                $tips .= '，'.$p_name.'逆行';
            }
            if($speed <= $average_speed/5)
            {
                $tips .= '，'.$p_name.'停滞';
            }
        }

        foreach ([2,3,4,5,6,7,8,9] as $i)
        {
            $i_deg = $tx_planet[$i]['deg'];// 太阳的度数
            $i_speed = $tx_planet[$i]['speed'];// 太阳的度数

            $i_start_sign = modSignId(floor($i_deg / 30) + 1);
            $i_end_sign = modSignId(floor(($i_deg + $i_speed)/30) + 1);

            if($i_start_sign != $i_end_sign)
            {
                $i_name = explode('|',config('astrolog.planets_name')[$i])[3];

                $i_sign_name = explode('|',config('astrolog.sign_name')[$i_end_sign])[3];

                $tips .= '，'.$i_name.'进入'.$i_sign_name;
            }
        }
        // 大十字，大风筝，大信封，大三角，T三角
        if(!empty($tx_structure['cross']))
        {
            $tips .= '，大十字';
        }
        if(!empty($tx_structure['kite']))
        {
            $tips .= '，大风筝';
        }
        if(!empty($tx_structure['envelop']))
        {
            $tips .= '，大信封';
        }
        if(!empty($tx_structure['trine']))
        {
            $tips .= '，大三角';
        }
        if(!empty($tx_structure['t_square']))
        {
            $tips .= '，T三角';
        }

        return $tips;
    }
}
